# ---
# 2 QUANTIFICANDO OS EFEITOS AGREGADOS DO ALINHAMENTO MINISTERIAL
# ---


# Pacotes
library(kableExtra)
library(tidyverse)
library(stargazer)
library(knitr)
library(geobr)
library(here)
library(lfe)


# Configuracoes
source(here("utils", "configs.R"))
source(here("utils", "funcoes.R"))


# Carrega os dados
load(here("data", "br_transfers_mun_1997_2016.Rda"))


# Baixa mapas
mapauf <- read_state()


# Prediz efeitos
mod <- felm(transfers_pc ~ align_party | mun_term_min + minis_year + mun_year | 0 |cod_ibge, data = base, exactDOF = T)

pred <- base %>%
  filter(!is.na(align_party)) %>%
  tidyr::expand(align_party) %>%
  predict_felm(mod, ., se.fit = T) %>%
  left_join(base, .) %>%
  mutate(cod_state = substr(cod_ibge, 1, 2))


# Grafico X - Desigualdade regional na alocacao de recursos
p1 <- pred %>%
  filter(population < 500000) %>%
  mutate(cod_state = as.numeric(cod_state)) %>%
  group_by(cod_state) %>%
  summarise(plus = sum(fit * population, na.rm = T)) %>%
  left_join(mapauf, ., by = c("code_state" = "cod_state")) %>%
  ggplot(aes(fill = plus)) +
  geom_sf(color = "black", size = 0.2) +
  scale_fill_distiller(direction = 1, palette = 6, 
                       label = function(x) x / 1000000,
                       breaks = seq(0, 600000000, by = 150000000),
                       guide = guide_legend(barwidth = 0.5, barheight = 8, 
                                            reverse = T)) +
  labs(fill = NULL, subtitle = "Milhões de reais") +
  theme_void(base_size = 11, base_family = fonte) +
  theme(legend.position = "bottom", plot.subtitle = element_text(hjust= 0.5))

p2 <- pred %>%
  filter(population < 500000) %>%
  mutate(cod_state = as.numeric(cod_state)) %>%
  group_by(cod_state) %>%
  summarise(plus = sum(fit * population, na.rm = T),
            minus = sum(transfers - (fit * population), na.rm = T),
            share = plus / minus) %>%
  left_join(mapauf, ., by = c("code_state" = "cod_state")) %>%
  ggplot(aes(fill = share)) +
  geom_sf(color = "black", size = 0.2) +
  scale_fill_distiller(direction = 1, palette = 6, 
                       label = function(x) paste0(x * 100, "%"),
                       limits = c(0, 0.08),
                       breaks = seq(0, 0.08, by = 0.02),
                       guide = guide_legend(barwidth = 0.5, barheight = 8, 
                                            reverse = T)) +
  labs(fill = NULL, subtitle = "Percentual") +
  theme_void(base_size = 11, base_family = fonte) +
  theme(legend.position = "bottom", plot.subtitle = element_text(hjust= 0.5))


p <- gridExtra::grid.arrange(p2, p1, ncol = 2)
ggsave(here("outputs", "map_quantificacao.pdf"), width = 15.7, height = 12, device = cairo_pdf, units = "cm", plot = p) # Textwidth 15.7



# Agricultura
preds <- pred %>%
  filter(ministry == "Agricultura") %>%
  filter(population < 500000) %>%
  mutate(regiao = case_when(
    
    substr(cod_state, 1, 1) == 1 ~ "Norte",
    substr(cod_state, 1, 1) == 2 ~ "Nordeste",
    substr(cod_state, 1, 1) == 3 ~ "Sudeste",
    substr(cod_state, 1, 1) == 4 ~ "Sul",
    substr(cod_state, 1, 1) == 5 ~ "Centro-Oeste")) %>%
  group_by(term, regiao) %>%
  do(simula(.$align_party, .$population, .$fit, .$se, 10, "milhoes")) %>%
  mutate(cenario = "Com prefeituras do PMDB") %>%
  bind_rows(
    
      base %>%
      filter(!is.na(align_party)) %>%
      tidyr::expand(align_party) %>%
      predict_felm(mod, ., se.fit = T) %>%
      left_join(base %>%
                  mutate(align_party = ifelse(party == "PMDB", 0, align_party)), .) %>%
      mutate(cod_state = substr(cod_ibge, 1, 2)) %>%
      filter(ministry == "Agricultura") %>%
      filter(population < 500000) %>%
      mutate(regiao = case_when(
        
        substr(cod_state, 1, 1) == 1 ~ "Norte",
        substr(cod_state, 1, 1) == 2 ~ "Nordeste",
        substr(cod_state, 1, 1) == 3 ~ "Sudeste",
        substr(cod_state, 1, 1) == 4 ~ "Sul",
        substr(cod_state, 1, 1) == 5 ~ "Centro-Oeste")) %>%
      group_by(term, regiao) %>%
      do(simula(.$align_party, .$population, .$fit, .$se, 10, "milhoes")) %>%
      mutate(cenario = "Sem prefeituras do PMDB")
  )

p <- preds %>%
  ungroup() %>%
  mutate(term = case_when(
    
    term == 1996 ~ "1997-2000",
    term == 2000 ~ "2001-2004",
    term == 2004 ~ "2005-2008",
    term == 2008 ~ "2008-2012",
    term == 2012 ~ "2012-2016"
  )) %>%
  mutate(term = fct_relevel(term, "1997-2000", "2001-2004", "2005-2008", "2008-2012", "2012-2016")) %>%
  
  ggplot(aes(x = term, y = est, linetype = cenario, group = cenario)) +
  geom_line() +
  facet_wrap(~ regiao) +
  theme_classic(base_size = tam_fonte, base_family = fonte) +
  theme(axis.text = element_text(color = "black"),
        axis.title = element_text(size = tam_leg),
        plot.subtitle = element_text(size = tam_leg + 1),
        legend.position = "bottom",
        strip.background = element_blank(),
        axis.text.x = element_text(angle = 90, hjust = 0)) +
  labs(linetype = NULL, y = "Milhões de reais\n", x = NULL)

ggsave(here("outputs", "plot_agricultura.pdf"), width = 15, height = 12, device = cairo_pdf, units = "cm", plot = p) # Textwidth 15.7


# Fim
rm(list = ls())
